<template>
  <div class="products-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 data-aos="fade-up">技术解决方案</h1>
        <p data-aos="fade-up" data-aos-delay="100">
          选择适合的服务套餐，即刻开启数字化转型之旅！
        </p>
      </div>
    </div>

    <!-- 套餐类型标签 -->
    <section class="packages-section">
      <div class="container">
        <el-tabs v-model="activeTab" class="package-tabs">
          <el-tab-pane label="技术服务套餐" name="tech">
            <!-- 套餐卡片 -->
            <div class="packages-grid">
              <div
                v-for="(pkg, index) in techPackages"
                :key="pkg.name"
                class="package-card"
                :class="pkg.featured ? 'featured' : ''"
                data-aos="fade-up"
                :data-aos-delay="index * 100"
              >
                <div v-if="pkg.featured" class="featured-badge">推荐</div>
                <div class="package-header">
                  <h3>{{ pkg.name }}</h3>
                  <p class="package-desc">{{ pkg.description }}</p>
                </div>
                <div class="package-price">
                  <span class="price-symbol">¥</span>
                  <span class="price-value">{{ pkg.price }}</span>
                  <span class="price-unit">{{ pkg.unit }}</span>
                </div>
                <div class="package-features">
                  <div class="feature-item highlight">
                    <el-icon><Star /></el-icon>
                    <span>{{ pkg.commitment }}</span>
                  </div>
                  <ul class="feature-list">
                    <li v-for="feature in pkg.features" :key="feature">
                      <el-icon color="#52c41a"><Check /></el-icon>
                      <span>{{ feature }}</span>
                    </li>
                  </ul>
                </div>
                <el-button type="primary" class="package-button" @click="handleConsult(pkg)">
                  立即咨询
                </el-button>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="定制开发套餐" name="custom">
            <div class="packages-grid">
              <div
                v-for="(pkg, index) in customPackages"
                :key="pkg.name"
                class="package-card"
                data-aos="fade-up"
                :data-aos-delay="index * 100"
              >
                <div class="package-header">
                  <h3>{{ pkg.name }}</h3>
                  <p class="package-desc">{{ pkg.description }}</p>
                </div>
                <div class="package-price">
                  <span class="price-symbol">¥</span>
                  <span class="price-value">{{ pkg.price }}</span>
                  <span class="price-unit">{{ pkg.unit }}</span>
                </div>
                <div class="package-features">
                  <ul class="feature-list">
                    <li v-for="feature in pkg.features" :key="feature">
                      <el-icon color="#52c41a"><Check /></el-icon>
                      <span>{{ feature }}</span>
                    </li>
                  </ul>
                </div>
                <el-button type="primary" class="package-button" @click="handleConsult(pkg)">
                  获取方案
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </section>

    <!-- 功能对比表 -->
    <section class="comparison-section">
      <div class="container">
        <h2 class="section-title" data-aos="fade-up">套餐功能对照表</h2>
        <p class="section-subtitle" data-aos="fade-up" data-aos-delay="100">
          详细了解各套餐包含的功能和服务
        </p>

        <div class="table-wrapper" data-aos="fade-up" data-aos-delay="200">
          <el-table :data="comparisonData" border class="comparison-table">
            <el-table-column prop="feature" label="功能列表" width="200" fixed />
            <el-table-column
              v-for="pkg in techPackages"
              :key="pkg.name"
              :label="pkg.name"
              align="center"
            >
              <template #default="{ row }">
                <span v-if="row[pkg.key] === true">
                  <el-icon color="#52c41a" :size="20"><Check /></el-icon>
                </span>
                <span v-else-if="row[pkg.key] === false">
                  <el-icon color="#ff4d4f" :size="20"><Close /></el-icon>
                </span>
                <span v-else>{{ row[pkg.key] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>

    <!-- 真实产品列表 -->
    <section class="real-products-section">
      <div class="container">
        <h2 class="section-title" data-aos="fade-up">我们的产品</h2>
        <p class="section-subtitle" data-aos="fade-up" data-aos-delay="100">
          查看我们为客户提供的实际产品案例
        </p>

        <div class="products-grid">
          <div
            v-for="(product, index) in products"
            :key="product.id"
            class="product-card"
            data-aos="fade-up"
            :data-aos-delay="index * 100"
            @click="$router.push(`/products/${product.id}`)"
          >
            <div class="product-image">
              <img v-if="product.cover_image" :src="product.cover_image" :alt="product.name" />
            </div>
            <div class="product-content">
              <h3>{{ product.name }}</h3>
              <p>{{ product.summary }}</p>
              <div class="product-link">
                查看详情 <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </div>
        </div>

        <div class="pagination">
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="fetchProducts"
          />
        </div>
      </div>
    </section>

    <!-- 常见问题FAQ -->
    <section class="faq-section">
      <div class="container">
        <h2 class="section-title" data-aos="fade-up">常见问题</h2>
        <p class="section-subtitle" data-aos="fade-up" data-aos-delay="100">
          有更多疑惑，请咨询在线客服
        </p>

        <el-collapse v-model="activeNames" class="faq-collapse" data-aos="fade-up" data-aos-delay="200">
          <el-collapse-item
            v-for="(faq, index) in faqs"
            :key="index"
            :name="index"
          >
            <template #title>
              <div class="faq-title">
                <el-icon color="#0066ff"><QuestionFilled /></el-icon>
                <span>{{ faq.question }}</span>
              </div>
            </template>
            <div class="faq-answer">{{ faq.answer }}</div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </section>

    <!-- CTA区域 -->
    <section class="cta-section">
      <div class="container">
        <div class="cta-content" data-aos="zoom-in">
          <h2>只要几秒钟，您就可以拥有属于您的专属服务</h2>
          <p>以上套餐不能满足，想要专属套餐定制？</p>
          <div class="cta-buttons">
            <el-button type="primary" size="large" @click="showContactDialog = true">
              定制套餐
            </el-button>
            <el-button size="large" @click="showWechat = true">
              咨询客服
            </el-button>
          </div>
        </div>
      </div>
    </section>

    <!-- 联系表单弹窗 -->
    <el-dialog 
      v-model="showContactDialog" 
      title="获取专属方案" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="contactForm" :rules="contactRules" ref="contactFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="contactForm.name" placeholder="请输入您的姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="contactForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="contactForm.company" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="需求" prop="message">
          <el-input 
            v-model="contactForm.message" 
            type="textarea" 
            :rows="4"
            placeholder="请简要描述您的需求"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showContactDialog = false">取消</el-button>
        <el-button type="primary" @click="submitContact">提交</el-button>
      </template>
    </el-dialog>

    <!-- 微信二维码弹窗 -->
    <el-dialog v-model="showWechat" title="微信咨询" width="350px" align-center>
      <div class="wechat-qrcode">
        <div class="qrcode-placeholder">
          <el-icon :size="100" color="#07c160"><ChatLineRound /></el-icon>
          <p>扫描二维码添加客服</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { getProducts, getPackagesData } from '@/api/portal'
import type { Product, ServicePackage, CustomPackage, PackageFeature, FAQ } from '@/types'
import { 
  Star, 
  Check, 
  Close, 
  ArrowRight, 
  QuestionFilled,
  ChatLineRound
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import AOS from 'aos'
import 'aos/dist/aos.css'

// 产品列表
const products = ref<Product[]>([])
const page = ref(1)
const pageSize = ref(9)
const total = ref(0)

// 标签页
const activeTab = ref('tech')
const activeNames = ref<number[]>([0])

// 弹窗控制
const showContactDialog = ref(false)
const showWechat = ref(false)
const contactFormRef = ref()

// 从API获取的数据
const servicePackages = ref<ServicePackage[]>([])
const customPackagesData = ref<CustomPackage[]>([])
const packageFeaturesData = ref<PackageFeature[]>([])
const faqsData = ref<FAQ[]>([])

// 技术服务套餐 - 转换为页面需要的格式
const techPackages = computed(() => {
  // 按照套餐类型排序，确保显示顺序：基础版 -> 标准版 -> 专业版 -> 企业版
  const sortOrder: Record<string, number> = {
    'basic': 1,
    'standard': 2,
    'professional': 3,
    'enterprise': 4
  }
  
  return servicePackages.value
    .filter(pkg => pkg.package_type) // 过滤掉没有类型的套餐
    .sort((a, b) => {
      const orderA = sortOrder[a.package_type] || 999
      const orderB = sortOrder[b.package_type] || 999
      return orderA - orderB
    })
    .map(pkg => ({
      key: pkg.package_type, // 直接使用套餐类型作为key，匹配功能对照表
      name: pkg.name,
      description: pkg.subtitle || pkg.description || '',
      price: pkg.price || '询价',
      unit: pkg.price_unit || '',
      commitment: pkg.suitable_for || '',
      featured: pkg.is_recommended === 1,
      features: pkg.features || []
    }))
})

// 定制开发套餐 - 转换为页面需要的格式
const customPackages = computed(() => {
  return customPackagesData.value.map(pkg => ({
    name: pkg.name,
    description: pkg.subtitle || pkg.description || '',
    price: pkg.price_range || '询价',
    unit: '',
    features: pkg.features || []
  }))
})

// 功能对比数据 - 转换为表格需要的格式
const comparisonData = computed(() => {
  if (!packageFeaturesData.value || packageFeaturesData.value.length === 0) {
    console.warn('套餐功能对照数据为空')
    return []
  }
  
  // 按分类分组
  const grouped = packageFeaturesData.value.reduce((acc: any, feature) => {
    const category = feature.feature_category || '其他'
    if (!acc[category]) {
      acc[category] = []
    }
    acc[category].push(feature)
    return acc
  }, {})
  
  // 转换为表格数据
  const result: any[] = []
  Object.keys(grouped).forEach(category => {
    grouped[category].forEach((feature: PackageFeature) => {
      const row: any = {
        feature: feature.feature_name,
        basic: feature.basic_plan || '-',
        standard: feature.standard_plan || '-',
        professional: feature.professional_plan || '-',
        enterprise: feature.enterprise_plan || '-'
      }
      
      // 转换布尔值显示
      Object.keys(row).forEach(key => {
        if (key !== 'feature') {
          if (row[key] === '√' || row[key] === '✓' || row[key] === 'true' || row[key] === '是') {
            row[key] = true
          } else if (row[key] === '×' || row[key] === '✗' || row[key] === 'false' || row[key] === '否') {
            row[key] = false
          }
        }
      })
      
      result.push(row)
    })
  })
  
  console.log('功能对照表数据转换完成:', result.length, '条记录')
  return result
})

// FAQ数据
const faqs = computed(() => {
  return faqsData.value.map(faq => ({
    question: faq.question,
    answer: faq.answer
  }))
})

// 联系表单
const contactForm = reactive({
  name: '',
  phone: '',
  company: '',
  message: ''
})

const contactRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  message: [{ required: true, message: '请描述您的需求', trigger: 'blur' }]
}

// 获取套餐页面数据（所有启用的套餐，不限制推荐/热门）
const fetchPackagesData = async () => {
  try {
    const res = await getPackagesData()
    servicePackages.value = res.data.service_packages || []
    customPackagesData.value = res.data.custom_packages || []
    packageFeaturesData.value = res.data.package_features || []
    faqsData.value = res.data.faqs || []
    
    console.log('=== 套餐数据加载完成 ===')
    console.log('技术服务套餐数量:', servicePackages.value.length)
    console.log('定制开发套餐数量:', customPackagesData.value.length)
    console.log('套餐功能对照数量:', packageFeaturesData.value.length)
    console.log('常见问题数量:', faqsData.value.length)
    
    if (packageFeaturesData.value.length > 0) {
      console.log('功能对照表样例数据:', packageFeaturesData.value[0])
    }
  } catch (error) {
    console.error('获取套餐数据失败', error)
  }
}

// 获取产品列表
const fetchProducts = async () => {
  try {
    const res = await getProducts({ page: page.value, page_size: pageSize.value })
    products.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    console.error('获取产品列表失败', error)
  }
}

// 处理咨询
const handleConsult = (pkg: any) => {
  contactForm.message = `我对${pkg.name}感兴趣，想了解更多详情。`
  showContactDialog.value = true
}

// 提交联系表单
const submitContact = async () => {
  const valid = await contactFormRef.value?.validate()
  if (valid) {
    // 这里可以调用API提交表单
    ElMessage.success('提交成功，我们会尽快联系您！')
    showContactDialog.value = false
    Object.assign(contactForm, { name: '', phone: '', company: '', message: '' })
  }
}

onMounted(() => {
  fetchPackagesData()  // 获取所有套餐数据
  fetchProducts()      // 获取产品列表
  // 初始化AOS动画库
  AOS.init({
    duration: 800,
    once: true,
    offset: 100
  })
})
</script>

<style scoped lang="scss">
.products-page {
  padding-top: 70px;
}

// 页面头部
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 100px 0 60px;
  text-align: center;

  h1 {
    font-size: 48px;
    font-weight: 700;
    margin-bottom: 16px;
  }

  p {
    font-size: 20px;
    opacity: 0.95;
  }
}

// 套餐区域
.packages-section {
  padding: 100px 0;
  background: #fff;
}

.package-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 60px;
  }
  
  :deep(.el-tabs__nav-wrap::after) {
    height: 0;
  }
  
  :deep(.el-tabs__item) {
    font-size: 18px;
    font-weight: 500;
    padding: 0 32px;
    height: 50px;
    line-height: 50px;
  }
  
  :deep(.el-tabs__active-bar) {
    height: 3px;
    background: linear-gradient(90deg, #0066ff, #00d4ff);
  }
}

.packages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 32px;
}

.package-card {
  position: relative;
  background: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: 2px solid transparent;
  
  &.featured {
    border-color: #0066ff;
    box-shadow: 0 8px 32px rgba(0, 102, 255, 0.2);
    
    .package-header h3 {
      color: #0066ff;
    }
  }
  
  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  }
}

.featured-badge {
  position: absolute;
  top: -12px;
  right: 32px;
  background: linear-gradient(135deg, #0066ff, #00d4ff);
  color: #fff;
  padding: 6px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 102, 255, 0.3);
}

.package-header {
  text-align: center;
  margin-bottom: 24px;
  
  h3 {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 12px;
    color: var(--text-primary);
  }
  
  .package-desc {
    font-size: 14px;
    color: var(--text-secondary);
    line-height: 1.6;
  }
}

.package-price {
  text-align: center;
  padding: 24px 0;
  border-top: 1px solid var(--border-light);
  border-bottom: 1px solid var(--border-light);
  margin-bottom: 24px;
  
  .price-symbol {
    font-size: 20px;
    color: var(--text-secondary);
    vertical-align: top;
    margin-right: 4px;
  }
  
  .price-value {
    font-size: 36px;
    font-weight: 700;
    color: var(--text-primary);
  }
  
  .price-unit {
    font-size: 16px;
    color: var(--text-secondary);
    margin-left: 4px;
  }
}

.package-features {
  .feature-item.highlight {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
    border-radius: 8px;
    margin-bottom: 16px;
    color: #0066ff;
    font-weight: 500;
    
    .el-icon {
      flex-shrink: 0;
    }
  }
  
  .feature-list {
    list-style: none;
    
    li {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 10px 0;
      font-size: 14px;
      color: var(--text-secondary);
      
      .el-icon {
        flex-shrink: 0;
        margin-top: 2px;
      }
    }
  }
}

.package-button {
  width: 100%;
  margin-top: 24px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
}

// 功能对比表
.comparison-section {
  padding: 100px 0;
  background: #fafafa;
}

.table-wrapper {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow-x: auto;
}

.comparison-table {
  :deep(.el-table__header) {
    th {
      background: #f5f7fa;
      color: var(--text-primary);
      font-weight: 600;
      font-size: 15px;
    }
  }
  
  :deep(.el-table__body) {
    td {
      font-size: 14px;
    }
  }
}

// 真实产品区域
.real-products-section {
  padding: 100px 0;
  background: #fff;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 32px;
  margin: 60px 0 40px;
}

.product-card {
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    
    .product-image img {
      transform: scale(1.05);
    }
  }
}

.product-image {
  width: 100%;
  height: 220px;
  overflow: hidden;
  background: #f5f5f5;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;
  }
}

.product-content {
  padding: 24px;
  
  h3 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 12px;
    color: var(--text-primary);
  }
  
  p {
    font-size: 14px;
    line-height: 1.6;
    color: var(--text-secondary);
    margin-bottom: 16px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.product-link {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--primary-color);
  font-weight: 500;
  font-size: 14px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

// FAQ区域
.faq-section {
  padding: 100px 0;
  background: #fff;
}

.faq-collapse {
  margin-top: 60px;
  border: none;
  
  :deep(.el-collapse-item) {
    background: #fff;
    border-radius: 12px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    border: none;
    overflow: hidden;
  }
  
  :deep(.el-collapse-item__header) {
    height: auto;
    padding: 20px 24px;
    background: #fff;
    border: none;
    font-size: 16px;
    font-weight: 500;
    
    &:hover {
      background: #fafafa;
    }
    
    &.is-active {
      border-bottom: 1px solid var(--border-light);
    }
  }
  
  :deep(.el-collapse-item__wrap) {
    border: none;
  }
  
  :deep(.el-collapse-item__content) {
    padding: 20px 24px;
    color: var(--text-secondary);
    line-height: 1.8;
  }
}

.faq-title {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.faq-answer {
  font-size: 15px;
}

// CTA区域
.cta-section {
  padding: 100px 0;
  background: linear-gradient(135deg, #0066ff 0%, #00d4ff 100%);
  color: #fff;
}

.cta-content {
  text-align: center;
  
  h2 {
    font-size: 36px;
    font-weight: 700;
    margin-bottom: 16px;
  }
  
  p {
    font-size: 18px;
    margin-bottom: 40px;
    opacity: 0.95;
  }
}

.cta-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  
  .el-button {
    padding: 16px 48px;
    font-size: 18px;
    font-weight: 600;
    border-radius: 50px;
    height: auto;
    
    &[type="primary"] {
      background: #fff;
      color: #0066ff;
      border: none;
      
      &:hover {
        background: #f5f5f5;
      }
    }
    
    &:not([type="primary"]) {
      background: rgba(255, 255, 255, 0.2);
      border: 2px solid #fff;
      color: #fff;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }
}

// 微信二维码
.wechat-qrcode {
  padding: 20px;
  text-align: center;
}

.qrcode-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 40px;
  background: #f5f5f5;
  border-radius: 12px;
  
  p {
    font-size: 16px;
    color: var(--text-secondary);
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .packages-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 80px 0 50px;
    
    h1 {
      font-size: 36px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .packages-section,
  .comparison-section,
  .real-products-section,
  .faq-section,
  .cta-section {
    padding: 60px 0;
  }
  
  .packages-grid {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
    gap: 24px;
    margin: 40px 0;
  }
  
  .table-wrapper {
    padding: 16px;
  }
  
  .cta-content {
    h2 {
      font-size: 28px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .cta-buttons {
    flex-direction: column;
    padding: 0 20px;
    
    .el-button {
      width: 100%;
    }
  }
}

@media (max-width: 480px) {
  .page-header {
    h1 {
      font-size: 28px;
    }
    
    p {
      font-size: 14px;
    }
  }
  
  .package-card {
    padding: 24px;
  }
  
  .package-price {
    .price-value {
      font-size: 28px;
    }
  }
  
  .cta-content {
    h2 {
      font-size: 24px;
    }
  }
}
</style>

